import { Number2 } from "@manycore/custom-miniapp-sdk"
import { Vector2 } from "three"

/** 向量 */
const v = Vector2
/** 获取向量 */
function getV(n: Number2) {
  return new v(n.x, n.y)
}
/** 批量获取向量 */
function getVs(n2: Number2[]) {
  const vecs = n2.map(n => new v(n.x, n.y))
  return vecs
}
/** 获取指定向量的垂直向量 */
function getPerpVector(vec: Vector2) {
  const { x, y } = vec
  const perp = new v(-y, x)
  perp.normalize();
  return perp
}
/** 获取圆弧圆心 */
export function getArcCenter(p1: Number2, p2: Number2, radius: number, isMinorArc: boolean, isCCW: boolean) {
  const { pow, sqrt } = Math
  const [p1v, p2v] = getVs([p1, p2])
  const dist = p1v.distanceTo(p2v)
  const len = sqrt(pow(radius, 2) - pow(dist / 2, 2))
  const midv = p1v.clone().add(p2v).divideScalar(2)
  const perpv = getPerpVector(p2v.clone().sub(p1v))
  if (isMinorArc && !isCCW || !isMinorArc && isCCW) {
    perpv.negate();
  }
  const center = midv.clone().add(perpv.multiplyScalar(len))
  const { x, y } = center
  return { x, y }
}
/** 获取圆弧的开始和结束角（弧度） */
export function getArc2Angle(center: Number2, p1: Number2, p2: Number2) {
  const [p1v, p2v] = getVs([p1, p2])
  const centerV = getV(center)
  const startAngle = p1v.clone().sub(centerV).angle()
  const endAngle = p2v.clone().sub(centerV).angle()
  return [startAngle, endAngle]
}
/** 获取椭圆弧的开始和结束角（弧度） */
export function getEllArc2Angle(p1: Number2, p2: Number2, isCCW: boolean, curve2d: any) {
  const { ccs2d: ccs, a, b } = curve2d
  ccs.dy = getPerpVector(getV(ccs.dx))
  let [startAngle, endAngle] = [p1, p2].map((p) => {
    const pv = getV(p)
    const vec = pv.sub(getV(ccs.o));
    const x = vec.dot(getV(ccs.dx)) / a;
    const y = vec.dot(getV(ccs.dy)) / b;
    let t = Math.atan2(y, x);
    if (t < 0) {
      t += 2 * Math.PI;
    }
    return t
  })
  var clockSign = isCCW ? 1 : -1;
  if (clockSign < 0) {
    startAngle = Math.PI * 2 - startAngle;
    endAngle = Math.PI * 2 - endAngle;
    return [startAngle, endAngle]
  }
  return [startAngle, endAngle]
}